<template>
  <el-dialog
    title="题型及数量"
    custom-class="center-dialog"
    :append-to-body="true"
    :visible.sync="visible"
    :before-close="close"
    width="1000px"
  >

    <div class="total-score">总分：{{totalScore}}分</div>
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column align="center" prop="questionType" label="题型" width="110">
        <template slot-scope="scope">
          {{ dict.label.topic_type[scope.row.questionType] }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="questionScore" label="每题分值" width="110">
        <template slot-scope="scope">
          {{scope.row.questionScore}}
          <span style="margin-left: 2px">分</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="题型数量">
        <el-table-column
          v-for="item in tableColumn"
          :key="item.value"
          align="center"
          :prop="item['count' + item.value]"
          :label="item.label"
        >
          <template slot-scope="scope">
            <template v-if="scope.row['max' + item.value] === 0"> -</template>
            <template v-else>
              <el-input-number
                v-model="scope.row['count' + item.value]"
                size="mini"
                controls-position="right"
                :precision="0"
                :min="0"
                :max="scope.row['max' + item.value]"
                style="width: 100px"
                @change="renderTotalScore"
              />
              <span style="margin-left: 6px; font-size: 12px">{{scope.row['max' + item.value]}}题可选</span>
            </template>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column align="center" prop="totalScore" label="总分" width="110">
        <template slot-scope="scope">
          {{scope.row.totalScore || 0}}
          <span style="margin-left: 2px">分</span>
        </template>
      </el-table-column>
    </el-table>
    <span slot="footer" class="dialog-footer">
      <el-button :disabled="loading" @click="close">取 消</el-button>
      <el-button v-loading="loading" type="primary" @click="onConfirm">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
  import { queryPapersQuestionCountProportions, queryQuestionCountProportions } from '@/api/juan/juanGenerate'

  export default {
    name: 'QuestionTypeDialog',
    components: {},
    dicts: ['topic_type', 'difficulty'],
    props: {
      loading: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        visible: false,
        title: '选择课程',
        tableData: [],
        tableColumn: [],
        totalScore: 0
      }
    },
    methods: {
      open(data) {
        this.visible = true

        if (data.type === 'questionRepos') {
          queryQuestionCountProportions({
            reposId: data.reposId,
            courseId: data.courseId,
            knowledgeIds: data.ids.join(',')
          })
            .then((res) => {
              this.renderData(res.data)
            })
            .catch()
        } else if (data.type === 'paperRegroup') {
          queryPapersQuestionCountProportions(data.ids.join(','))
            .then((res) => {
              this.renderData(res.data)
            })
            .catch()
        }
      },
      close() {
        if (!this.loading) {
          this.visible = false
        }
      },
      renderData(data) {
        let column = []
        let rows = []
        for (let i = 0; i < data.length; i++) {
          let item = data[i]

          let columnIndex = column.findIndex((cItem) => {
            return cItem.value === item.questionEasy
          })
          if (columnIndex === -1) {
            column.push({
              value: item.questionEasy,
              label: this.dict.label.difficulty[item.questionEasy]
            })
          }

          let rowsIndex = rows.findIndex((cItem) => {
            return cItem.questionType === item.questionType && cItem.questionScore === item.questionScore
          })
          if (rowsIndex === -1) {
            rows.push({
              questionType: item.questionType,
              questionScore: item.questionScore,
            })
          }
        }

        function findQuestion(questionType, questionScore, questionEasy) {
          for (let i = 0; i < data.length; i++) {
            let item = data[i]
            if (item.questionType === questionType && item.questionScore === questionScore && item.questionEasy === questionEasy) {
              return item
            }
          }

          return null
        }

        this.tableColumn = column

        this.tableData = rows.map((item) => {
          let option = { ...item, totalScore: 0 }
          for (let j = 0; j < column.length; j++) {
            let cItem = column[j]
            let currQuestion = findQuestion(item.questionType, item.questionScore, cItem.value)
            option['max' + cItem.value] = currQuestion ? currQuestion.questionNum : 0
            option['count' + cItem.value] = 0
          }

          return option
        })

        this.renderTotalScore();
      },
      onConfirm() {
        let paperData = this.tableData
          .map((item) => {
            let options = { ...item, children: [] }
            for (const key in item) {
              if (/^count\d+$/.test(key) && item[key] > 0) {
                options.children.push({
                  easy: key.substring(5),
                  count: item[key]
                })
              }
            }
            return options
          })
          .filter((item) => {
            return item.children && item.children.length > 0
          })

        let generateData = []
        for (let i = 0; i < paperData.length; i++) {
          let item = paperData[i]
          for (let j = 0; j < item.children.length; j++) {
            let cItem = item.children[j]
            generateData.push({
              questionType: item.questionType,
              questionNum: cItem.count,
              questionEasy: cItem.easy,
              questionScore: item.questionScore
            })
          }
        }

        if (generateData.length > 0) {
          this.$emit('confirm', generateData)
        } else {
          this.$message.warning('请设置题目数量')
        }
      },
      renderTotalScore() {
        this.totalScore = 0;
        this.tableData.forEach(item => {
          item.totalScore = 0;
          for (const key in item) {
            if (/^count\d+$/.test(key) && item[key] > 0) {
              item.totalScore = item.totalScore + (item[key] * item.questionScore)
            }
          }
          this.totalScore = this.totalScore + item.totalScore;
        });
      }
    }
  }
</script>

<style lang="scss" scoped>
  .total-score {
    text-align: right;
    margin-bottom: 10px;
    margin-top: -20px;
  }
  .table-row-attr + .table-row-attr {
    margin-top: 10px;
  }

  .question-types {
    margin: -16px 0;

    .type-item {
      display: flex;
      align-items: center;
      margin: 16px 0;

      .type-attr {
        display: flex;
        align-items: center;
        margin-right: 30px;
        font-size: 16px;
        color: #363b55;

        &.attr-label {
          font-weight: bold;
        }
      }
    }
  }

</style>
